package org.catpay.modules.app.service.impl;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.catpay.modules.app.dao.SharePageDao;
import org.catpay.modules.app.utils.DrawingUtils;
import org.catpay.modules.app.vo.SharePageInfo;
import org.iherus.codegen.qrcode.QrcodeConfig;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

@Service("qiniuyunService")
public class QiniuyunServiceImpl extends ServiceImpl<SharePageDao, SharePageInfo> {
	@Value("${qiniu.ak}")
	private String accessKey;
	@Value("${qiniu.sk}")
	private String secretKey;
	@Value("${qiniu.bucket}")
	private String bucket;
	@Value("${qiniu.cdn}")
	private String cdn;

	@Value("${img.path}")
	private String path;
	@Value("${img.oImg}")
	private String oImg;

	@Value("${img.logoImg}")
	private String logoImg;

	public String getToken() {
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		return upToken;
	}

	public String uploadFile(String filePath, String key) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// 如果是Windows情况下，格式是 D:\\qiniu\\test.png
		String localFilePath = filePath;
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket, key);
		try {
			Response response = uploadManager.put(localFilePath, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			key = putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return key;
	}

	public String uploadByest(byte[] bytes, String key) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(bytes, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			key = putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return key;
	}

	public String uploadStream(ByteArrayInputStream byteInputStream, String key) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
		// ByteArrayInputStream byteInputStream=new
		// ByteArrayInputStream(uploadBytes);
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
			Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			key = putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
		}
		return key;
	}

	public String uploadMultipartFile(MultipartFile multipartFile, String type) throws IOException {
		String fileName = multipartFile.getOriginalFilename();
		String suffix = StringUtils.substringAfterLast(fileName, ".");

		// 若没有后缀，则添加默认后缀为jpg
		if (StringUtils.isEmpty(suffix)) {
			suffix = "jpg";
		}
		String key = type + "_" + IdUtil.fastSimpleUUID() + "." + suffix;
		uploadByest(multipartFile.getBytes(), key);
		return key;
	}

	public String convertImageUrl(String key) {
		if (StringUtils.isNotEmpty(key)) {
			return cdn + key;
		}
		return null;

	}

	public String makeSharePage(String content, String desc, String key, String img, Long userId) {
		QrcodeConfig config = new QrcodeConfig().setBorderSize(2).setPadding(10).setMasterColor("#00BFFF")
				.setLogoBorderColor("#B0C4DE");
		try {
			String shareImgPath = path + "share_" + key + ".png";
			DrawingUtils.generateImg(img,
					new SimpleQrcodeGenerator(config).setLogo(logoImg).generate(content).getImage(), desc,
					shareImgPath);
			String returnUrl = uploadFile(shareImgPath, "share_" + key + ".jpg");
			if (StrUtil.isNotBlank(returnUrl)) {
				SharePageInfo sp = new SharePageInfo(cdn + returnUrl, userId);
				sp.insert();
				return cdn + returnUrl;
			}
			return "";

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}
